#!/data/Software/mydan/perl/bin/perl -I/data/Software/mydan/Connector/lib -I/data/Software/mydan/Connector/private/lib
use strict;
use warnings;
use Code;
use YAML::XS;
use FindBin qw( $RealBin );

$| ++;

=head1 SYNOPSIS

=cut

return sub
{
    my %param = @_;

    my ( $Config, $envname ) = @param{qw( Config envname )};

    die "envinfo config undef" unless $Config->{envinfo};

    my %macro = ( %{$Config->{envinfo}}, envname => $envname );


    die "config/api.connector.x.x.conf.Template null" unless my $conf = `cat $RealBin/../config/api.connector.x.x.conf.Template`;

    my @conf;

    my $port = $Config->{port};

    push @conf, 'upstream connector_api{';

    for my $node ( keys %{$Config->{host}} )
    {
        for my $port ( $port->{api}{from} .. $port->{api}{to} )
        {
            push @conf, "  server $Config->{host}{$node}{inip}:$port;" if $port % 3 eq 0;
        }
        push @conf, "";
    }

    push @conf, '}';


    push @conf, 'upstream connector_api_internal{';

    for my $node ( keys %{$Config->{host}} )
    {
        for my $port ( $port->{api}{from} .. $port->{api}{to} )
        {
            push @conf, "  server $Config->{host}{$node}{inip}:$port;" if $port % 3 eq 1;
        }
        push @conf, "";
    }

    push @conf, '}';


    push @conf, 'upstream connector_api_default{';

    for my $node ( keys %{$Config->{host}} )
    {
        for my $port ( $port->{api}{from} .. $port->{api}{to} )
        {
            push @conf, "  server $Config->{host}{$node}{inip}:$port;" if $port % 3 eq 2;
        }
        push @conf, "";
    }

    push @conf, '}';


    die "domainname undef" unless $macro{domainname};
    for my $k ( keys %macro )
    {
        $conf =~ s#\[\[:$k:\]\]#$macro{$k}#g;
    }

    open my $H , ">$RealBin/../conf/api.connector.open-c3.org.conf" or die "open conf/api.connector.open-c3.org.conf fail:$!";
    for( @conf )
    {
        print $H "$_\n";
    }
    print $H $conf;
    close $H;
}
